import React, {Component} from 'react';
import NavigationBar from '../../Common/NavigationBar/NavigationBar.jsx';
import $ from 'jquery';
import DialogNative from '../../Common/Dialog/Dialog.jsx';
import DialogHeader from '../../Common/Dialog/DialogHeader.jsx';
import DialogBody from '../../Common/Dialog/DialogBody.jsx';
import DialogFooter from '../../Common/Dialog/DialogFooter.jsx';
import WeUI from 'react-weui';
import {CSS} from "../styles/meetingRoom.css";
import cnCity from "../components/cnCity.jsx";
import dateFormat from 'dateformat';

const {Cells, Cell, CellHeader, CellBody, CellFooter, Input, Popup, PopupHeader, Form, FormCell, Picker, CityPicker, Label, Toast, Toptips, Checkbox,Dialog} = WeUI;


function jsonDateFormat(jsonDate) {
    try {
        return jsonDate.replace(/\//g, "-");
    } catch (ex) {//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
        return jsonDate;
    }
}

var meetingRooms = [];
let commonPeriodList = [];
const TwoHourMinter = 120;
let userSelectedTeamId = 0;
let show_day = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'];
export default class MeetingRoom extends Component {
    constructor(props) {
        super(props);
        this.LeftClick = this.LeftClick.bind(this);
        this.RightClick = this.RightClick.bind(this);
        this.getRoomList = this.getRoomList.bind(this);
        this.hideLoading = this.hideLoading.bind(this);
        this.showErrorTips = this.showErrorTips.bind(this);
        this.resetRoomList = this.resetRoomList.bind(this);
        this.filterChange = this.filterChange.bind(this);
        this.showError = this.showError.bind(this);
        this.state = {
            meetingRoomDateFilter: {
                teamId: 0,
                teamName: "请选择企业",
                incubatorId: "1",
                incubatorName: "",
                buildingId: 1,
                buildingName: "那个楼",
                floorId: 1,
                floorName: "第几层",
                floorSequence: 3,
                bookingDate: dateFormat(new Date(), "yyyy/mm/dd"),
                teams: []
            },
            meetingRoomList: meetingRooms,
            commonPeriodList: [],
            showErrorTips: false,
            errorMsg: "网络不是很稳定，请重试！",
            showLoading: true,
            showErrorComponent: false,
        };
    }

    componentWillMount() {
    }

    hideLoading() {
        this.setState({
            showLoading: false
        });
    }

    showErrorTips(msg) {
        this.setState({
            showErrorTips: true,
            showLoading: false,
            errorMsg: msg ? msg : this.state.errorMsg
        });

        setTimeout(() => {
            this.setState({
                showErrorTips: false,
                errorMsg: ""
            })
        }, 2000);
    }

    componentDidMount() {
        let accessFilterUrl = "/MeetingRoom/booking/filter/default";
        fetch(getHost() + accessFilterUrl, {
            credentials: "include"
        }).then(response => response.json()).then(json => {
            if (json.success) {
                if (!json.data.teams || json.data.teams.length === 0) {
                    this.setState({
                        showErrorComponent: true,
                        showLoading: false
                    });

                    return;
                }
                this.getRoomList(json.data);
            } else {
                this.showErrorTips(json.error.message);
                console.log("error to get default filter");
            }
        }).catch(e => {
            this.showErrorTips();
            console.log("error to get default filter");
        });

    }

    showError(msg) {
        this.setState({
            showErrorTips: false,
            errorMsg: msg ? msg : "网络不给力，请重试！"
        });
    }

    getRoomList(filter) {
        if (filter) {
            console.log("get room List userSelectedTeamId:" + filter.teamId);
            userSelectedTeamId = filter.teamId || 0;
            let tempFilter = Object.assign({}, filter);
            //remove unused params
            delete tempFilter.incubators;
            delete tempFilter.teams;
            delete tempFilter.incubatorBuildings;
            delete tempFilter.incubatorFloors;
            if (!tempFilter.floorId || tempFilter.floorId == 0) {
                delete tempFilter.floorId;
            }

            if (!tempFilter.buildingId || tempFilter.buildingId == 0) {
                delete tempFilter.buildingId;
            }
            let roomListUrl = "/MeetingRoom/booking/room/list?filter=" + encodeURIComponent(JSON.stringify(tempFilter));
            fetch(getHost() + roomListUrl, {
                credentials: "include"
            }).then(response => response.json()).then(json => {
                if (json.success) {
                    commonPeriodList = json.data.sortedPeriods;
                    this.setState({
                        meetingRoomList: json.data.meetingRoomDateVos,
                        meetingRoomDateFilter: filter
                    });
                    this.hideLoading();
                } else {
                    this.resetRoomList();
                    this.showErrorTips(json.error.message);
                    return;
                }
            }).catch(e => {
                this.showErrorTips(e);
            });
        }

    }

    resetRoomList() {
        this.setState({
            meetingRoomList: []
        });
    }

    LeftClick() {
    }

    RightClick() {
        location.hash = '/MeetingRoomHistory?teamId=' + userSelectedTeamId;
        return;
    }

    filterChange(meetingRoomFilter) {
        if (meetingRoomFilter) {
            console.log("filter change :" + meetingRoomFilter.teamId);
            this.getRoomList(meetingRoomFilter);
        }
    }


    render() {
        return (
            <div style={{height: '100%', width: '100%'}}>
                <NavigationBar Title="会议室预约" LeftBar="true" LeftTitle="返回"
                               LeftIconSrc="/iot-meeting/assets/images/common/nav_back_icon.png" LeftClick={this.LeftClick}
                               RightBar="true" RightTitle="预约记录" RightClick={this.RightClick}/>
                <MeetingRoomFilter filterChange={this.filterChange}
                                   showCells={this.state.showErrorComponent}
                                   meetingRoomDateFilter={this.state.meetingRoomDateFilter}/>
                <MeetingRoomList rooms={this.state.meetingRoomList}/>
                <Toptips type="warn" show={this.state.showErrorTips}>
                    {this.state.errorMsg}
                </Toptips>
                <Toast icon="loading" show={this.state.showLoading}>加载中...</Toast>
                <ErrorPage show={this.state.showErrorComponent}/>
            </div>
        )
    }
}

class ErrorPage extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        if (this.props.show) {
            return (
                <div className="errorPage-container">
                    <img src="/iot-meeting/assets/images/meetingRoom/errorPage.png" className="errorPage"/>
                </div>
            );
        } else {
            return <div></div>;
        }
    }
}

class MeetingRoomFilter extends Component {
    constructor(props) {
        super(props);
        this.meetingDate = this.meetingDate.bind(this);
        this.handleUserSelectTeam = this.handleUserSelectTeam.bind(this);
        this.handleUserSelectAddress = this.handleUserSelectAddress.bind(this);
        this.getTeamsList = this.getTeamsList.bind(this);
        this.getIncubatorBuildings = this.getIncubatorBuildings.bind(this);
        this.getBuildings = this.getBuildings.bind(this);
        this.getMeetingDate = this.getMeetingDate.bind(this);
        userSelectedTeamId = this.props.meetingRoomDateFilter.teamId || 0;
        this.state = {
            incubatorId: this.props.meetingRoomDateFilter.incubatorId || 0,
            meeting_picker_show: false,
            showTeamPicker: false,
            buildings: [],
            meeting_address: "点击选择",
            week_input: ""
        };
    }

    componentDidMount() {
        this.getBuildings();
    }

    hide() {
        this.setState({
            picker_show: false,
            meeting_picker_show: false,
            showTeamPicker: false
        })
    }

    getMeetingDate() {
        $('#meeting_date').focus();
    }

    meetingDate(e) {
        let meetingFilter = this.props.meetingRoomDateFilter;
        console.log("date_week:" + e.target.value + "," + show_day[new Date(e.target.value).getDay() - 1]);
        this.setState({week_input: e.target.value});
        meetingFilter.bookingDate = e.target.value;
        this.props.filterChange(meetingFilter);
    }

    handleUserSelectAddress(text) {
        let buildingId = 0, floorId = 0;
        if (!text || text == null) {
            if (this.state.buildings && this.state.buildings[0] && this.state.buildings[0].floors && this.state.buildings[0].floors[0]) {
                text = this.state.buildings[0].name + " " + this.state.buildings[0].floors[0].name;
                buildingId = this.state.buildings[0].id;
                floorId = this.state.buildings[0].floors[0].id;
            }
        } else {
            let addressArr = text.split(" ");
            if (addressArr && addressArr.length >= 2) {
                let buildingText = addressArr[0];
                let floorText = addressArr[1];
                this.state.buildings && this.state.buildings.forEach(item => {
                    if (item.name == buildingText) {
                        buildingId = item.id;
                        item.floors && item.floors.forEach(floor => {
                            if (floor.name == floorText) {
                                floorId = floor.id;
                            }
                        })
                    }
                });
            }
        }
        console.log("buildId:" + buildingId);
        console.log("floorId:" + floorId);
        let meetingFilter = this.props.meetingRoomDateFilter;
        meetingFilter.buildingId = buildingId;
        meetingFilter.floorId = floorId;
        this.props.filterChange(meetingFilter);
        this.setState({meeting_address: text, meeting_picker_show: false})
    }

    handleUserSelectTeam(selected) {
        let meetingFilter = this.props.meetingRoomDateFilter;
        let selectedValue = "";
        if (this.props.meetingRoomDateFilter.teams && this.props.meetingRoomDateFilter.teams[selected]) {
            selectedValue = this.props.meetingRoomDateFilter.teams[selected].name;
            userSelectedTeamId = this.props.meetingRoomDateFilter.teams[selected].id;
            console.log("userSelectedTeamId:" + userSelectedTeamId);
        }
        meetingFilter.teamName = selectedValue;
        meetingFilter.teamId = userSelectedTeamId;
        this.hide();
        this.props.filterChange(meetingFilter);
    }

    getTeamsList() {
        let userSelectTeamGroup = [], resultGroup = [];
        if (this.props.meetingRoomDateFilter.teams) {
            this.props.meetingRoomDateFilter.teams.forEach(item => {
                userSelectTeamGroup.push({label: item.name});
            })
        }
        resultGroup.push({items: userSelectTeamGroup})
        return resultGroup;
    }

    getBuildings() {
        if (this.props.meetingRoomDateFilter.incubatorId) {
            let getBuildingUrl = "/MeetingRoom/booking/building/list?incubatorId=" + this.props.meetingRoomDateFilter.incubatorId;
            fetch(getHost() + getBuildingUrl, {
                credentials: "include"
            }).then(res => res.json()).then(json => {
                if (json.success) {
                    this.setState({
                        buildings: json.data
                    });
                }
            }).catch(e => {
                console.log("error on query building info.");
            });
        }
    }

    getIncubatorBuildings() {
        let incubators = [];
        this.state.buildings && this.state.buildings.forEach((item) => {
            let floors = [];
            item.floors && item.floors.forEach(floor => {
                floors.push({name: floor.name, id: floor.id});
            });
            let incubator = {
                "name": item.name,
                "id": item.id,
                "sub": floors
            };
            incubators.push(incubator);
        });
        return incubators;

    }


    render() {
        let bookingDate = this.state.week_input ? this.state.week_input : this.props.meetingRoomDateFilter.bookingDate,
            bookingTeamName = this.props.meetingRoomDateFilter.teamName;
        // bookingDate = jsonDateFormat(bookingDate) + " " + show_day[new Date(bookingDate).getDay() - 1];
        bookingDate = jsonDateFormat(bookingDate);
        let userSelectTeamGroup = this.getTeamsList();
        let incubators = this.getIncubatorBuildings();
        console.log("filter userSelectedTeamId:" + userSelectedTeamId);
        return (
            <div>
                {(incubators.length > 0) ?
                    <CityPicker
                        data={incubators}
                        onCancel={e => this.setState({meeting_picker_show: false})}
                        selected={[]}
                        onChange={this.handleUserSelectAddress}
                        show={this.state.meeting_picker_show}
                    />
                    : ""
                }
                <Picker
                    onChange={this.handleUserSelectTeam}
                    groups={userSelectTeamGroup}
                    show={this.state.showTeamPicker}
                    onCancel={e => this.setState({showTeamPicker: false})}
                    lang={{rightBtn: '完成',leftBtn:'取消'}}
                />
                {this.props.showCells ?
                    "" :
                    <Cells style={{marginTop: 0}}>
                        <Cell>
                            <CellHeader>
                                <img src="/iot-meeting/assets/images/meetingRoom/team_icon.png" alt=""
                                     style={{display: `block`, width: `20px`, marginRight: `5px`}}/>
                            </CellHeader>
                            <CellBody><span
                                className="filter-title">使用企业</span></CellBody>
                            <CellFooter className="filter-item-footer">
                                <div onClick={e => this.setState({showTeamPicker: true})} className="filter-item"><p
                                    className="overflow-elli">{bookingTeamName ? bookingTeamName : "请选择企业"}</p></div>
                            </CellFooter>
                        </Cell>
                        <Cell>
                            <CellHeader>
                                <img src="/iot-meeting/assets/images/meetingRoom/address_icon.png" alt=""
                                     style={{display: `block`, width: `20px`, marginRight: `5px`}}/>
                            </CellHeader>
                            <CellBody>
                                <span className="filter-title">开会楼层</span></CellBody>
                            <CellFooter className="filter-item-footer">
                                <Input className="filter-item overflow-elli" type="button"
                                       value={this.state.meeting_address}
                                       onClick={e => {
                                           e.preventDefault();
                                           e.stopPropagation();
                                           this.setState({meeting_picker_show: true});
                                           return;
                                       }}
                                       placeholder="点击选择"
                                       readOnly={true}
                                       style={{textAlign: "right"}}
                                />
                            </CellFooter>
                        </Cell>
                        <Cell>
                            <CellHeader>
                                <img src="/iot-meeting/assets/images/meetingRoom/time_icon.png" alt=""
                                     style={{display: `block`, width: `20px`, marginRight: `5px`}}/>
                            </CellHeader>
                            <CellBody><span className="filter-title">会议日期</span></CellBody>
                            {/*<CellFooter className="filter-item-footer">*/}
                            <div style={{width: "20rem", position: "relative", textAlign: "right"}}
                                 onClick={this.getMeetingDate}>
                                <Input id="meeting_date" className="filter-item overflow-elli " type="date"
                                       onChange={this.meetingDate}/>
                                <div className="meeting_input filter-item overflow-elli ">{bookingDate}</div>
                            </div>
                            {/*</CellFooter>*/}
                        </Cell>
                    </Cells>
                }
            </div>
        );
    }
}


class MeetingRoomItemHeader extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div className="meeting-room-header">{this.props.name}{this.props.bookingBtn}
            </div>
        );
    }
}

class MeetingRoomPeriod extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        let periodItemWidth = {width: "calc(100% / " + commonPeriodList.length / 2 + ")"};
        let periodItemStyle = null;
        if (this.props.period && this.props.period.past) {
            periodItemStyle = "periodItem periodItem-past";
        } else if (this.props.period && this.props.period.booked) {
            periodItemStyle = "periodItem periodItem-booked";
        } else if (this.props.period && this.props.period.bookedByCurrentTeam) {
            periodItemStyle = "periodItem periodItem-bookedByTeam";
        } else {
            periodItemStyle = "periodItem";
        }
        return (
            <div className={periodItemStyle} style={periodItemWidth}></div>
        );
    }

}


/* meeting room period 必须排序过，否则页面直接抱错。。。。*/
class MeetingRoomPeriods extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        let amPeriodArr = [], pmPeriodArr = [], amTimePeriodArr = [], pmTimePeriodArr = [];
        let twoHourUnit = 0;
        let userPeriodMap = {};
        this.props.periodVos && this.props.periodVos.forEach(item => {
            userPeriodMap["" + item.periodCode] = item;
        });

        let periodTimeStyle = {width: "calc(100% / " + (commonPeriodList.length / 8 + 1) + ")"};
        amTimePeriodArr.push(<div className="periodTime" style={periodTimeStyle}>0:00</div>);
        pmTimePeriodArr.push(<div className="periodTime" style={periodTimeStyle}>12:00</div>);
        commonPeriodList && commonPeriodList.forEach((meetingRoomPeriod, index) => {
            let item = userPeriodMap[meetingRoomPeriod.code];
            twoHourUnit += (meetingRoomPeriod.endHour - meetingRoomPeriod.startHour) * 60 + (meetingRoomPeriod.endMinute - meetingRoomPeriod.startMinute);
            if (meetingRoomPeriod && meetingRoomPeriod.amPm === "am") {
                amPeriodArr.push(<MeetingRoomPeriod period={item} key={"period" + index}/>);
                if (twoHourUnit === TwoHourMinter) {
                    amTimePeriodArr.push(<div className="periodTime" key={"am" + index}
                                              style={periodTimeStyle}>{meetingRoomPeriod.endHour}:00</div>);
                    twoHourUnit = 0;
                }
            } else {
                pmPeriodArr.push(<MeetingRoomPeriod period={item} key={"period" + index}/>);
                if (twoHourUnit === TwoHourMinter) {
                    pmTimePeriodArr.push(<div className="periodTime" key={"pm" + index}
                                              style={periodTimeStyle}>{meetingRoomPeriod.endHour}:00</div>);
                    twoHourUnit = 0;
                }
            }
        });

        return (
            <div>
                {amTimePeriodArr}
                <div className="clearFloat"></div>
                <div>{amPeriodArr}</div>
                <div className="clearFloat"></div>
                <div>{pmTimePeriodArr}</div>
                <div className="clearFloat"></div>
                <div>{pmPeriodArr}</div>
                <div className="clearFloat"></div>
            </div>
        )
    }

}

class MeetingRoomItem extends Component {
    constructor(props) {
        super(props);
        this.selectedBookingTime = this.selectedBookingTime.bind(this);
        this.userCheckedPeriod = this.userCheckedPeriod.bind(this);
        this.closeDialog = this.closeDialog.bind(this);
        this.togglePmPeriods = this.togglePmPeriods.bind(this);
        this.toggleAmPeriods = this.toggleAmPeriods.bind(this);
        this.showSelectPeriodError = this.showSelectPeriodError.bind(this);
        this.setUserSelectedPeriods = this.setUserSelectedPeriods.bind(this);
        this.getTotalTime = this.getTotalTime.bind(this);
        this.checkContinuousTimePeriod = this.checkContinuousTimePeriod.bind(this);
        this.getPeriodStatus = this.getPeriodStatus.bind(this);
        this.hideToptipsAuto = this.hideToptipsAuto.bind(this);
        this.state = {
            showBookingTime: false,
            showConfirmBooking: false,
            toggleAmPeriods: false,
            togglePmPeriods: false,
            userSelectPeriods: [],
            userBeginPeriod: null,
            userEndPeriod: null,
            showSelectPeriodError: false,
            showSelectPeriodErrorMsg: "请选择连续的开会时间段",
            rechargePackageBalance:{},
            meetingRoomInfo:{}, //确认弹框需要展示信息
            meetingRoomPayType:1, //1:个人预定 2:企业预定
            showIOS2: false,
            style2: {
                title: '会议室预定',
                buttons: [
                    {
                        type: 'default',
                        label: '取消',
                        onClick: this.hideDialog.bind(this)
                    },
                    {
                        type: 'primary',
                        label: '确定',
                        onClick: this.confirmDialog.bind(this)
                    }
                ]
            }
        };
    }

    hideDialog() {
        this.setState({showIOS2:false,showBookingTime:true,showConfirmBooking:true});
    }

    getPercent(curNum, totalNum){
        curNum = parseFloat(curNum);
        totalNum = parseFloat(totalNum);
        if (isNaN(curNum) || isNaN(totalNum)) {
            return '-';
        }
        return totalNum <= 0 ? 0 : (Math.round(curNum / totalNum * 10000) / 100.00);
    }


    confirmDialog(){
        let residueTime = this.getPercent(this.state.rechargePackageBalance.remainLength,this.state.rechargePackageBalance.totalLength);
        location.hash = "/MeetingRoomBuyTime?residueTime="+residueTime+"&teamName="+this.state.rechargePackageBalance.teamName+"";
    }


    toggleAmPeriods() {
        this.setState({
            toggleAmPeriods: !this.state.toggleAmPeriods,
        });
    }

    togglePmPeriods() {
        this.setState({
            togglePmPeriods: !this.state.togglePmPeriods
        });
    }

    closeDialog() {
        this.setState({
            showConfirmBooking: false,
        });

    }

    selectedBookingTime(e) {
        //确认用户已经选择了开会时间
        if (!this.state.userSelectPeriods && this.state.userSelectPeriods.length == 0) {
            this.showSelectPeriodError("请选择预定时间！");
            return;
        }

        //确认用户是否选择了连续的开会时间
        if (this.checkContinuousTimePeriod()) {
            this.showSelectPeriodError("请选择连续的时间区间！");
            return;
        }
        let bookingTotalHours = this.getTotalTime();
        let totalAmount = this.props.meetingRoomItem.meetingRoomVo.hourlyPrice * bookingTotalHours;
        let roomId = this.props.meetingRoomItem.meetingRoomId;
        let bookingDate = this.props.meetingRoomItem.bookingDate;
        let startPeriodCode = this.state.userBeginPeriod.code;
        let endPeriodCode = this.state.userEndPeriod.code;
        let calcPriceUrl = "/MeetingRoom/booking/price/calculation?bookingDate=" + bookingDate
            + "&meetingRoomId=" + roomId
            + "&startPeriodCode=" + startPeriodCode
            + "&endPeriodCode=" + endPeriodCode;
        let self = this;
        fetch(getHost() + calcPriceUrl, {
            credentials: "include"
        }).then(res => res.json()).then(json => {
            if (json.success) {
                //获取会议室加油包
                fetch(getHost() + "/MeetingRoom/booking/balance?teamId="+userSelectedTeamId+"", {
                    credentials: "include"
                }).then(res => res.json()).then(data => {
                    if (data.success) {
                        self.setState({
                            showConfirmBooking: true,
                            totalAmount: json.data.calculatePrice,
                            rechargePackageBalance:data.data,
                            meetingRoomInfo:json.data
                        });
                    } else {
                        self.showSelectPeriodError(data.error.message);
                    }
                }).catch(e => {
                    self.showSelectPeriodError("服务器异常!");
                });

            } else {
                self.showSelectPeriodError(json.error.message);
            }
        }).catch(e => {
            self.showSelectPeriodError("服务器异常!");
        });

    }

    getTotalTime() {
        if (this.state.userBeginPeriod && this.state.userEndPeriod) {
            let totalHours = (this.state.userEndPeriod.endHour - this.state.userBeginPeriod.startHour) + (this.state.userEndPeriod.endMinute - this.state.userBeginPeriod.startMinute) / 60;
            return totalHours;
        } else {
            return 0;
        }
    }


    callWxPay(meetingRoomOrderId) {
        if (meetingRoomOrderId) {
            let getMeetingRoomPayInfo = "/wxpay/createOrder/MeetingRoom?" + "meetingRoomOrderId=" + meetingRoomOrderId;
            fetch(getHost() + getMeetingRoomPayInfo, {
                credentials: "include"
            }).then(res => res.json()).then(json => {
                if (json.success) {
                    WeixinJSBridge.invoke(
                        'getBrandWCPayRequest',
                        json.data,
                        function (res) {
                            //不管失败或者成果，都会跳转到历史订单页面
                            if (res.err_msg == "get_brand_wcpay_request:ok") {// 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                                markDataRequestFlag();
                                window.location.hash = '/MeetingRoomHistory?teamId=' + userSelectedTeamId;
                                return;
                            } else {  //支付失败或者取消，直接跳转到：合约信息中。
                                markDataRequestFlag();
                                window.location.hash = '/MeetingRoomHistory?teamId=' + userSelectedTeamId;
                                return;
                            }
                        }
                    );
                }
            }).catch(e => {

            });

        } else {
            this.showSelectPeriodError("网络不给力，请重试！");
            return;
        }
    }

    orderMeetingRoom(type) {
        // let remainLength = this.state.meetingRoomInfo.calculatePrice / this.state.meetingRoomInfo.hourlyPrice
        if(type === 1){ //个人预定
            let roomId = this.props.meetingRoomItem.meetingRoomId;
            let bookingDate = this.props.meetingRoomItem.bookingDate;
            let startPeriodCode = this.state.userBeginPeriod.code;
            let endPeriodCode = this.state.userEndPeriod.code;
            let payAmount = this.state.totalAmount;
            let formData = new FormData();
            let makeOrderUrl = "/MeetingRoom/booking/order";
            formData.append("teamId", userSelectedTeamId);
            formData.append("bookingDate", bookingDate);
            formData.append("meetingRoomId", roomId);
            formData.append("startPeriodCode", startPeriodCode);
            formData.append("endPeriodCode", endPeriodCode);
            formData.append("payAmount", payAmount);
            formData.append("useRechargePackage",false);
            fetch(getHost() + makeOrderUrl, {
                method: "POST",
                credentials: "include",
                body: formData
            }).then(res => res.json()).then(json => {
                if (json.success) {
                    //call pay TODO
                    if (parseFloat(this.state.totalAmount) === 0) {  //if amount is equal to 0, go to history.
                        location.hash = '/MeetingRoomHistory?teamId=' + userSelectedTeamId;
                    } else {
                        this.callWxPay(json.data.id);
                    }
                } else {
                    location.hash = '/MeetingRoomHistory?teamId=' + userSelectedTeamId;
                }
            }).catch(e => {
                this.showSelectPeriodError("网络不给力，请重试！");
            });
        }else{//企业预定
            let bookingTotalTime = this.getTotalTime();
            if(parseFloat(bookingTotalTime) > parseFloat(this.state.rechargePackageBalance.remainLength)){
                this.setState({showIOS2:true,showBookingTime:false,showConfirmBooking:false});
                return;
            }
            let self = this;
            let roomId = this.props.meetingRoomItem.meetingRoomId;
            let bookingDate = this.props.meetingRoomItem.bookingDate;
            let startPeriodCode = this.state.userBeginPeriod.code;
            let endPeriodCode = this.state.userEndPeriod.code;
            let payAmount = this.state.totalAmount;
            let formData = new FormData();
            let makeOrderUrl = "/MeetingRoom/booking/order";
            formData.append("teamId", userSelectedTeamId);
            formData.append("bookingDate", bookingDate);
            formData.append("meetingRoomId", roomId);
            formData.append("startPeriodCode", startPeriodCode);
            formData.append("endPeriodCode", endPeriodCode);
            formData.append("payAmount", payAmount);
            formData.append("useRechargePackage",true);
            fetch(getHost() + makeOrderUrl, {
                method: "POST",
                credentials: "include",
                body: formData
            }).then(res => res.json()).then(json => {
                if (json.success) {
                    location.hash = '/MeetingRoomHistory?teamId=' + userSelectedTeamId;
                } else {
                    self.showSelectPeriodError(json.error.message);
                }
            }).catch(e => {
                self.showSelectPeriodError("网络不给力，请重试！");

            });
        }
    }

    showSelectPeriodError(msg) {
        this.setState({
            showSelectPeriodError: true,
            showSelectPeriodErrorMsg: msg
        });

        this.hideToptipsAuto();
    }

    hideToptipsAuto() {
        setTimeout(() => {
            this.setState({
                showSelectPeriodError: false
            });
        }, 2000);
    }

    userCheckedPeriod(e) {
        let userCheckPeriod = parseInt(e.target.value);
        let userSelectedPeriods = this.state.userSelectPeriods;
        let index = userSelectedPeriods.indexOf(userCheckPeriod);
        if (index > -1) {
            //remove from it;
            userSelectedPeriods.splice(index, 1);
            this.setUserSelectedPeriods(userSelectedPeriods);
        } else {
            if (userSelectedPeriods && userSelectedPeriods.length >= 1) {
                //选择连续的：在已经选择的之前或者之后都可以。
                userSelectedPeriods.push(userCheckPeriod);
                this.setUserSelectedPeriods(userSelectedPeriods);
            } else {
                userSelectedPeriods.push(userCheckPeriod);
                this.setUserSelectedPeriods(userSelectedPeriods);

            }
        }
    }

    checkContinuousTimePeriod() {
        //用户选择连续的区间
        let isContinuous = false;
        let userSelectedPeriods = this.state.userSelectPeriods;
        if (userSelectedPeriods.length >= 2) {
            let prePeriodOrder = 0;
            for (let i = 0; i < userSelectedPeriods.length; i++) {
                if (i === 0) {
                    prePeriodOrder = userSelectedPeriods[i];
                } else if (parseInt(prePeriodOrder) === parseInt((userSelectedPeriods[i] - 1))) {
                    prePeriodOrder = userSelectedPeriods[i];
                    continue;
                } else {
                    isContinuous = true;
                    break;
                }
            }
        }
        return isContinuous;
    }

    setUserSelectedPeriods(userSelectedPeriods) {
        userSelectedPeriods = userSelectedPeriods.sort((a1, a2) => a1 - a2);
        if (userSelectedPeriods && userSelectedPeriods.length > 0) {
            //用户选择连续的区间
            let isNotContinuous = this.checkContinuousTimePeriod();
            this.setState({
                userSelectPeriods: userSelectedPeriods,
                userBeginPeriod: this.getPeriodByPeriodOrder(userSelectedPeriods[0]),
                userEndPeriod: this.getPeriodByPeriodOrder(userSelectedPeriods[userSelectedPeriods.length - 1]),
                showSelectPeriodError: isNotContinuous,
                showSelectPeriodErrorMsg: "请选择连续的时间区间！"
            });
            if (isNotContinuous) {
                this.hideToptipsAuto();
            }
        } else {
            this.setState({
                userSelectPeriods: userSelectedPeriods,
                showSelectPeriodError: false,
                userBeginPeriod: null,
                userEndPeriod: null,
            });
        }

    }

    getPeriodByPeriodOrder(periodOrder) {
        for (let i = 0; i < commonPeriodList.length; i++) {
            if (periodOrder && commonPeriodList[i].periodOrder === parseInt(periodOrder)) {
                return commonPeriodList[i];
            }
        }
    }

    getPeriodStatus(periodOrder) {
        if (this.props.meetingRoomItem.periodVos && this.props.meetingRoomItem.periodVos.length) {
            for (let i = 0; i < this.props.meetingRoomItem.periodVos.length; i++) {
                let periodVO = this.props.meetingRoomItem.periodVos[i];
                if (periodVO && periodOrder === periodVO.periodOrder) {
                    return periodVO;
                }
            }
        } else {
            return null;
        }
    }

    checkOverTime(meetingRoomPeriod) {
        //先判断选择日期日期是不是当天
        let now = new Date();
        let bookingDate = new Date(this.props.meetingRoomItem.bookingDate.replace(/-/g, "\/"));
        if (bookingDate > now) { //日期大于当天预定
            return false;
        } else { //当天预定
            if (now.getHours() < meetingRoomPeriod.endHour) { //如果当前小时<结束小时时间 返回false  //获取当前时间以后的时间
                return false;
            } else if (now.getHours() === meetingRoomPeriod.endHour) { //如果当前小时=会议结束小时
                if (now.getMinutes() < meetingRoomPeriod.endMinute) { //如果当前系统分钟 < 结束分钟
                    return false;
                } else {
                    return true;
                }
            } else {
                return true;
            }
        }
    }

    formatMinute(minute) {
        if (minute === 0) {
            return "00";
        } else if (minute > 0 && minute < 10) {
            return "0" + minute;
        } else {
            return minute;
        }
    }

    //选择付款方式
    bookingMeetingRoomType(type){
        this.setState({meetingRoomPayType:type})
    }


    render() {
        let bookingBtn = <div className="floatRight">
            <div className="BookingBtn" onClick={e => this.setState({showBookingTime: true})}>预定</div>
            <div className="clearFloat"></div>
        </div>;
        let amPeriods = [], pmPeriods = [];
        (commonPeriodList.length > 0) && commonPeriodList.forEach(item => {
            let isUserChecked = this.state.userSelectPeriods.indexOf(parseInt(item.periodOrder)) >= 0;
            let periodStatus = this.getPeriodStatus(item.periodOrder);
            let isOvertime = this.checkOverTime(item);//获取大于当前时间的时间列表
            let checkBox = <Checkbox name="checkbox1" disabled={periodStatus.booked} readOnly={periodStatus.booked}
                                     value={item.periodOrder} onChange={this.userCheckedPeriod}
                                     defaultChecked={isUserChecked}/>;
            if (!isOvertime || this.state.userSelectPeriods.indexOf(item.periodOrder) >= 0) {
                if (item.amPm === "am") {
                    amPeriods.push(<FormCell checkbox key={item.periodOrder}>
                        <CellHeader>
                            {checkBox}
                        </CellHeader>
                        <CellBody className={periodStatus.booked ? "booked" : ""}>{item.code}</CellBody>
                        {periodStatus.booked ? <CellFooter>
                            <div className="booked">不可预定</div>
                        </CellFooter> : ""}
                    </FormCell>);
                } else {
                    pmPeriods.push(<FormCell checkbox key={item.periodOrder}>
                        <CellHeader>
                            {checkBox}
                        </CellHeader>
                        <CellBody className={periodStatus.booked ? "booked" : ""}>{item.code}</CellBody>
                        {periodStatus.booked ? <CellFooter>
                            <div className="booked">不可预定</div>
                        </CellFooter> : ""}
                    </FormCell>);
                }
            }

        });

        let amToggleImg, pmToggleImg;
        if (this.state.toggleAmPeriods) {
            amToggleImg = <img src="/iot-meeting/assets/images/meetingRoom/untoggle_icon.png" className="toggleImg"/>;
        } else {
            amToggleImg = <img src="/iot-meeting/assets/images/meetingRoom/toggle_icon.png" className="untoggleImg"/>;
        }
        if (this.state.togglePmPeriods) {
            pmToggleImg = <img src="/iot-meeting/assets/images/meetingRoom/untoggle_icon.png" className="toggleImg"/>;
        } else {
            pmToggleImg = <img src="/iot-meeting/assets/images/meetingRoom/toggle_icon.png" className="untoggleImg"/>;
        }

        let roomPrice = this.props.meetingRoomItem.meetingRoomVo.hourlyPrice;
        console.log("roomPrice:" + roomPrice);
        let displayRoomPrice = "¥" + roomPrice + "元/小时";
        if (parseFloat(roomPrice) === 0) {
            displayRoomPrice = "免费";
        }

        //筛选支付方式
        let user_backgroundColor = "";
        let team_backgroundColor = "";
        let  tempArea = "";
        if(this.state.meetingRoomPayType === 1){
            user_backgroundColor = "#0088EC";
            team_backgroundColor = "#FFFFFF";
            tempArea = <div>
                <div className="pay-meeting-room-title">支付费用：</div>
                <div className="pay-meeting-room-amount">{this.state.totalAmount === 0 ? "免费" : "¥" + this.state.totalAmount}</div>
                <div className="btnGroup">
                    <div className="confirmPayBtn" onClick={this.orderMeetingRoom.bind(this,1)}>确认预约并付费</div>
                </div>
            </div>
        }else{
            user_backgroundColor = "#FFFFFF";
            team_backgroundColor = "#0088EC";
            tempArea = <div>
                <div className="pay-meeting-room-title">加油包剩余:<span className="pay-meeting-room-value">{this.state.rechargePackageBalance.remainLength}小时</span></div>
                <div className="pay-meeting-room-title">扣除时间：</div>
                <div className="pay-meeting-room-amount">{this.getTotalTime()}小时</div>
                <div className="btnGroup">
                    <div className="confirmPayBtn" onClick={this.orderMeetingRoom.bind(this,2)}>确认扣除</div>
                </div>
            </div>
        }

        return (
            <div className="meetingRoomItem">
                <MeetingRoomItemHeader
                    name={this.props.meetingRoomItem.meetingRoomVo.meetingRoomSerialNum + this.props.meetingRoomItem.meetingRoomVo.meetingRoomName}
                    bookingBtn={bookingBtn}
                />


                <div className="meeting-room-desc">
                    容纳人数：<span className="desc-space">{this.props.meetingRoomItem.meetingRoomVo.seatNum}</span>
                    楼层：<span className="desc-space">{this.props.meetingRoomItem.meetingRoomVo.floorName}</span>
                    单价：<span className="desc-space">{displayRoomPrice}</span>
                </div>

                <MeetingRoomPeriods periodVos={this.props.meetingRoomItem.periodVos}/>
                <Popup
                    show={this.state.showBookingTime}
                    onRequestClose={e => this.setState({showBookingTime: false})}>
                    <div style={{height: '100vh', overflow: 'scroll'}}>

                        <div>
                            <PopupHeader
                                left="取消"
                                right="确认选择"
                                leftOnClick={e => this.setState({showBookingTime: false})}
                                rightOnClick={this.selectedBookingTime}
                            />
                            <Cells className="overrideCellsMargin">
                                <Cell className="booingTimePeriodSummary">
                                    <CellHeader>
                                        <img src="/iot-meeting/assets/images/meetingRoom/hours_icon.png" alt=""
                                             style={{display: `block`, width: `20px`, marginRight: `5px`}}/>
                                    </CellHeader>
                                    <CellBody>
                                        <span>开会时间段</span>
                                    </CellBody>
                                    <CellFooter className="boodingTimeSummary">
                                        <span>{this.state.userBeginPeriod ? this.state.userBeginPeriod.startHour + ":" + this.formatMinute(this.state.userBeginPeriod.startMinute) : "开始时间"}</span>
                                        ~<span>{this.state.userEndPeriod ? this.state.userEndPeriod.endHour + ":" + this.formatMinute(this.state.userEndPeriod.endMinute) : "结束时间"}</span>
                                    </CellFooter>
                                </Cell>
                            </Cells>
                        </div>

                        <div>
                            {amPeriods.length > 0 ?
                                <Cells className="overrideCellsMargin">
                                    <div onClick={this.toggleAmPeriods}>
                                        <Cell>
                                            <CellHeader className="amPmHeader">
                                                <span className="marginRight">AM</span><span>上午(00:00-12:00)</span>
                                            </CellHeader>
                                            <CellBody>
                                            </CellBody>
                                            <CellFooter>
                                                {amToggleImg}
                                            </CellFooter>
                                        </Cell>
                                    </div>
                                    {(this.state.toggleAmPeriods) ?
                                        <Form checkbox className="toggleIt"> {amPeriods}</Form> :
                                        <Form checkbox className="unToggleIt">{amPeriods}</Form>}
                                </Cells>
                                : ""}

                            {pmPeriods.length > 0 ?
                                <Cells className="overrideCellsMargin">
                                    <div onClick={this.togglePmPeriods}>
                                        <Cell>
                                            <CellHeader>
                                                <div className="amPmHeader"><span
                                                    className="marginRight">PM</span><span>下午(12:00-24:00)</span></div>
                                            </CellHeader>
                                            <CellBody>
                                            </CellBody>
                                            <CellFooter>
                                                {pmToggleImg}
                                            </CellFooter>
                                        </Cell>
                                    </div>
                                    {(this.state.togglePmPeriods) ?
                                        <Form checkbox className="toggleIt"> {pmPeriods}</Form> :
                                        <Form checkbox className="unToggleIt">{pmPeriods}</Form>}
                                </Cells>
                                : ""}
                        </div>
                    </div>
                </Popup>
                <DialogNative show={this.state.showConfirmBooking} close={this.closeDialog}>
                    <DialogHeader>费用支付</DialogHeader>
                    <DialogBody>
                        <div className="pay-meeting-room-title">会议室名称:<span className="pay-meeting-room-value">{this.state.meetingRoomInfo.meetingRoomName}</span></div>
                        <div className="pay-meeting-room-title">会议室地点:<span className="pay-meeting-room-value">{this.state.meetingRoomInfo.meetingRoomSerialNum}</span></div>
                        <div className="pay-meeting-room-title">会议室时间:<span className="pay-meeting-room-value">{this.state.userEndPeriod ? this.state.userBeginPeriod.startHour + ":" + this.formatMinute(this.state.userBeginPeriod.startMinute) + "~" + this.state.userEndPeriod.endHour + ":" + this.formatMinute(this.state.userEndPeriod.endMinute) : ""}</span></div>
                        <div className="pay_type_box">
                            <div className="meeting-room_payType">支付方式:</div>
                            <div className="user-booking"  style={{backgroundColor:user_backgroundColor,color:team_backgroundColor}}  onClick={this.bookingMeetingRoomType.bind(this,1)}>个人预定</div>
                            <div className="team_booking"  style={{backgroundColor:team_backgroundColor,color:user_backgroundColor}}   onClick={this.bookingMeetingRoomType.bind(this,2)}>企业预定</div>
                        </div>
                        <div style={{clear:"both"}}></div>
                        {tempArea}
                    </DialogBody>
                    <DialogFooter>
                        <div>会议室使用规则：</div>
                        <div>准时开会，准时结束会议，请准时参加；</div>
                        <div>使用企业套餐扣除套餐使用时间</div>
                    </DialogFooter>
                </DialogNative>
                <Toptips type="warn" show={this.state.showSelectPeriodError}>
                    {this.state.showSelectPeriodErrorMsg}
                </Toptips>
                <Dialog type="ios" title={this.state.style2.title} buttons={this.state.style2.buttons} show={this.state.showIOS2}>
                    加油包剩余时间不足,请充值!
                </Dialog>
            </div>
        );
    }
}

class MeetingRoomList extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        let rooms = [];
        this.props.rooms && this.props.rooms.forEach((item, index) => {
            rooms.push(<MeetingRoomItem meetingRoomItem={item} key={index}/>);
        })
        return (<div className="room-list-container">
            {rooms}
        </div>)
    }
}
